package com.qd.p2p.web.action.notify.repay;

import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import com.qd.p2p.web.action.notify.TradeNotifyBaseAction;
import com.qd.p2p.web.action.notify.TradeNotifyValueEvent;
import com.qdlc.p2p.biz.processor.event.BorrowRepayValueEvent;
import com.qdlc.p2p.biz.processor.task.pay.BorrowRepayPayTaskProcessor;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.common.constant.NotifyUrl;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.util.MailUtil;
import com.qdlc.p2p.dal.dto.TppTradeLog;

/**
 * 还款 - 代收 回调通知
 * 根据回调的状态 进行实际的业务处理
 * 业务层封装在Service中 为事务保持一致性
 *
 * @author wuaj
 */
public class NotifyCollectAction extends TradeNotifyBaseAction {

    /** 业务名 */
    private final static String BUSINESS_NAME = "还款";

    /** 业务处理名 */
    private final static String PROCESS_NAME = "代收本息";

    @Resource
    @Qualifier("borrowRepayCollectService")
    private CollectPayService borrowRepayCollectService;

    @Resource
    @Qualifier("borrowRepayPayService")
    private CollectPayService borrowRepayPayService;
    /**
     * PS 还款回调处理
     */
    @Override
    @Action(value = NotifyUrl.REPAY_NOTIFY_COLLECT_URL)
    public void doAction() {
        actionHandle();
    }

    @Override
    public String getBusinessName() {
        return BUSINESS_NAME;
    }

    @Override
    public String getProcessName() {
        return PROCESS_NAME;
    }

    /**
     * 完成状态 业务处理
     */
    @Override
    public void finishHandle(TradeNotifyValueEvent event) {
        borrowRepayCollectService.tradeFinish(event.getTppTradeLog(), event.getDepositStatus(), event.getDepositAmount());
        try {
            // 多笔代付
            List<TppTradeLog> tppTradeLogs = borrowRepayPayService.createOrders(event.getTppTradeLog());
            // 代付放入队列中
            BorrowRepayValueEvent borrowRepayValueEvent = new BorrowRepayValueEvent();
            borrowRepayValueEvent.setTppTradeLogs(tppTradeLogs);
            borrowRepayValueEvent.setTaskProcessorClass(BorrowRepayPayTaskProcessor.class);
            //将事件放入到队列中
            QueueHandlers.put(borrowRepayValueEvent);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 通知重新发起 代付还款金(本金+利息)
            MailUtil.sendMail("本息代付-订单生成失败", "本息代付订单生成失败", "");
        }
    }

    /**
     * 成功状态 业务处理
     */
    @Override
    public void successHandle(TradeNotifyValueEvent event) {
        borrowRepayCollectService.tradeSuccess(event.getTppTradeLog(), event.getDepositStatus());
    }

    /**
     * 失败状态 业务处理
     */
    @Override
    public void failHandle(TradeNotifyValueEvent event) {
        borrowRepayCollectService.tradeFail(event.getTppTradeLog(), event.getDepositStatus());
    }
}
